package com.xxkj.drugtraceability.scan

import android.content.Context
import android.media.AudioManager
import android.media.MediaPlayer
import com.xxkj.drugtraceability.R
import java.io.IOException
import java.util.*

/**
 * Author: mp2
 * Date: 2021/4/25 17:02
 * Describe:
 */
object SoundPlayer {
    private val mediaPlayer = MediaPlayer()
    private val toPlayList: MutableList<Int> = ArrayList()
    var play_raw = 0

    /**
     * 播放扫描声音
     *
     * @param c
     */
    fun playSound(c: Context) {
        playAssetSound(c, R.raw.beep)
    }
    /**
     * 播放声音方法，传入context和本地raw下资源
     * @param c
     * @param raw
     */

    private fun playAssetSound(context: Context, raw: Int) {
        if (mediaPlayer.isPlaying) {
            if (play_raw != raw) toPlayList.add(raw)
            return
        }
        val c = context.applicationContext
        play_raw = raw
        try {
            val afd = c.resources.openRawResourceFd(raw)
            mediaPlayer.reset()
            mediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC)
            mediaPlayer.setDataSource(afd.fileDescriptor, afd.startOffset, afd.length)
            mediaPlayer.prepare()

            mediaPlayer.setOnCompletionListener {
                try {
                    afd.close()
                    if (toPlayList.size > 0) {
                        playAssetSound(c, toPlayList[0])
                        toPlayList.removeAt(0)
                    }
                } catch (e: IOException) {
                    e.printStackTrace()
                }
            }
            mediaPlayer.start()
        } catch (e: Exception) {
            e.printStackTrace()
        }
    }

    fun playSoundAlertError(context: Context) {
        toPlayList.add(R.raw.alert_error)
        playAssetSound(context, R.raw.alert_error)
    }
}